/*
#################################
# Metadata Enhancement for Repositories (MER) 
# This software is an overlay repository search interface that uses a 
# text mined index of terms.
# Copyright (C) 2011  Rory McNicholl (University of London Computer Centre), Robert Drinkall (University College London)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Contact repositories@ulcc.ac.uk
# http://www.ulcc.ac.uk

##################################
*/


jQuery.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    jQuery.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

//(function(jQuery){

	var config = {mer_dir: "/merlin", repo_url: "http://myrepo.ac.uk/", repo_oai_id: "oai:myrepo.ac.uk", repo_id: "myrepo"};
	var search = {};

	/* LASSO in the manner of ajax */
	function render_no_results(){
		jQuery("#results").html('<div class="fieldset" id="results-content"><h1><span>No results</span></h1><h2><a href="#help_box_results"><img alt="?" src="'+config.mer_dir+'/images/help.png"/></a></h2><p>No results found for search string "'+merlin.search_string+'"</p></div>');
		jQuery('#results-content h2 a').fancyZoom({directory: config.mer_dir+'/images', width: 600});
		render_no_terms();
	}
	function render_no_terms() {
		var no_terms_text = 'No terms found from result set of search for "'+merlin.search_string+'".';
		var back_button = '<p id="back_to_prev_search" style="margin-left: 10px;"><button>Back to previous result</button></p>';

		if(!merlin.current_rs_terms){
			no_terms_text = 'No terms found for document "'+search.viewing_title+'".';
			back_button = '<p id="back_to_result_set" style="margin-left: 10px;"><button>Back to result set terms</button></p>';
		}
		
		jQuery("#terms_cloud .fieldset").html('<h1><span>No terms</span></h1><h2><a href="#help_box_terms_cloud"><img alt="?" src="'+config.mer_dir+'/images/help.png"/></a></h2><div><p style="margin-left: 10px;">'+no_terms_text+'</p>'+back_button+'</div>');



		jQuery("#terms_cloud .fieldset div").width(jQuery("#terms").width()-5);
		var l = jQuery("#terms").position().left+jQuery("#terms").width();
		jQuery("#terms_cloud .fieldset h2 a").css({position: 'absolute', top: jQuery("#terms").position().top-15, left: l-35});
		jQuery('#terms_cloud .fieldset h2 a').fancyZoom({directory: config.mer_dir+'/images', width: 600});
		
		jQuery("#back_to_result_set button").click(function(){
			merlin.current_rs_terms=true;
			merlin_request();
			return false;
		});
		jQuery("#back_to_prev_search button").click(function(){
			get_search_history(false);
			re_search(jQuery(search.searches).find("index").eq(-2).text());
			return false;
		});
	}
	function render_results(){
		
		search.num_recs = jQuery("totalResults", search.results).text();
		search.from = jQuery("startIndex", search.results).text();
		search.page_size = jQuery("itemsPerPage", search.results).text();
		search.to = parseInt(search.from)+parseInt(search.page_size);

		var paging = "";
		if(parseInt(search.to) >= parseInt(search.num_recs))
			search.to = search.num_recs;
		paging = '<div id="res_paging">';
//		if(debug)
//			console.log(search.from+"-"+search.page_size);
		if(parseInt(search.from)-parseInt(search.page_size)>-1) paging += '<span id="res_prev">&lt; prev</span>';
		if(parseInt(search.to) < parseInt(search.num_recs)) paging += '<span id="res_next">next &gt;</span>';
		paging += '</div>';
		var res_intro = "Showing "+(parseInt(search.from)+1)+" to "+search.to+" of "+search.num_recs;
		var page;

		if(search.browse_tree == search.results){
			b_page = search.browse_page;
			b_id = search.browse_id;
			b_p_id = search.browse_p_id;
	/*		page = jQuery("page", search.results).text();
			var index = jQuery("index", search.results).text();
			var index_value = jQuery(index, search.results).find("id").text();
			var index_label = jQuery(index, search.results).find("label").text();
			if(index == 'year')
				index_value = index_value.substr(0,4);
			res_intro += " ("+index+" is "+index_label+")";
	*/
		}
		if(jQuery("#results div.fieldset").length==0){
			jQuery("#results").html('<div class="fieldset" id="results-content"><h1><span>'+res_intro+'</span></h1><h2><a href="#help_box_results"><img alt="?" src="'+config.mer_dir+'/images/help.png"/></a></h2>'+paging+'<div id="result_list"><div><ul id="top_list"></ul></div><ul id="main_list"></ul></div></div>');
			jQuery('#results-content h2 a').fancyZoom({directory: config.mer_dir+'/images', width: 600});
		}else{
			jQuery("#results ul#main_list").html('');
			jQuery("#res_paging").replaceWith(paging);
			jQuery("#results-content h1 span").html(res_intro);
		}
		search.res_ind = parseInt(search.from);
		jQuery("item",search.results).each(function(){
			render_result_row(jQuery(this));
		});
		if(jQuery("#top_list li").length)
			jQuery("#results-content ul#main_list li").css({opacity: 0.3});

		var column_height = jQuery("#terms_cloud .fieldset").height()-jQuery("#results-content h2").height()-jQuery("#res_paging").height()+9;//-jQuery("#results-content h2").height();

		jQuery("#results li:first").addClass("first-li");
		jQuery("#results div.fieldset div#result_list").css({height: column_height+"px", overflow: "scrolling"})
	/*
		jQuery(".article_forward").live('click' ,function(){
			if(jQuery(this).closest("li").attr("id").search("detail")<0)
				var record_id = jQuery(this).closest("li").attr("id").split("search_")[1];
			else
				var record_id = jQuery(this).closest("li").attr("id").split("search_detail_")[1];
			var request = config.mer_dir+"/ajax/article_forward.php";
			var data = {record_id: record_id};
			jQuery.ajax({
				type: "POST",
				url: request,
				data: data,
				async: false,
				success: function(xml){
					if(jQuery("url", xml).length==1)
						window.open(jQuery("url", xml).text());
					else if(jQuery("url", xml).length>1){
						if(jQuery("#url_choice").length==0){
							jQuery("body").append('<div id="url_choice"><ul></ul></div><a id="url_choice_link" href="#url_choice" style="display: none;">not here</a>');
						}else{
							jQuery("#url_choice").replaceWith('<div id="url_choice"><ul></ul></div>');
							jQuery("#url_choice_link").replaceWith('<a id="url_choice_link" href="#url_choice" style="display: none;">not here</a>');
						}
						jQuery("url", xml).each(function(){
							jQuery("#url_choice ul").append('<li><a href="'+jQuery(this).text()+'" target="_new">'+jQuery(this).text()+'</a></li>');
						});
						jQuery("#url_choice_link").fancyZoom({directory: config.mer_dir+'/images', width: 600});
						jQuery("#url_choice_link").trigger("click");
					}
	//				else
						//do the abstract thing

				},
				error: function (data, status, e){
					alert("rss request error: "+status);
				}
			});
			return false;
		});
	*/

		jQuery(".article_details").live('click', function(){
			var article = jQuery(this);
			jQuery("#results .article_details").removeClass("viewing_details");

			record_id = jQuery(this).closest("li").attr("id").split("search_")[1];
			if(record_id.match(/t_/)) //could be from toplist
				record_id = jQuery(this).closest("li").attr("id").split("search_t_")[1];

			var request = "/cgi/export/"+record_id+"/XML";
	//		if(debug) console.log(request);	
			jQuery.ajax({
				type: "GET",
				url: request,
				async: false,
				success: function(xml){
					add_to_viewed_stack(record_id,article,xml);
					render_details(xml);
				},
				error: function (data, status, e){
					if(debug) console.log("Request failed: "+status+"\n"+request+"\n"+dump(data));
				}
			});
		
		});
		jQuery("#res_prev").click(function(){
			if(search.browse_tree == search.results){
				browse(b_id,b_p_id,parseInt(b_page)-1);
			}else
				do_search(jQuery("#search_form"),search.from-search.page_size);
		});
		jQuery("#res_next").click(function(){
			if(search.browse_tree == search.results){
				browse(b_id,b_p_id,parseInt(b_page)+1);
			}else
				do_search(jQuery("#search_form"),search.to);
			return false;
		});
	}
	function render_result_row(record,termid,classname){
		search.res_ind++;
		if(jQuery(record).find("title").length>0)
			var title = jQuery(record).find("title").text();
		else
			var title = jQuery(record).find("citation").text();

		var rec_id = jQuery(record).find("guid").text();
		if(rec_id.length ==0)
			rec_id = jQuery(record).find("record_id").text();
		else
			rec_id = rec_id.substring(rec_id.search(/\/\d+/)+1,rec_id.length-1);
		var year = jQuery(record).find("pubDate").text();
		year = year.substring(0,16);

		if(!termid){
			var li = '<li id="search_'+rec_id+'">'+'<div class="text"><small>'+search.res_ind+'.</small>&nbsp;<a href="#" class="article_details">'+title;
			if(year) li +=' ('+year+')';
			li += '</a></div></li>';

			jQuery("#results ul#main_list").append(li);
			if(jQuery.inArray(rec_id,search.viewed)>=0){
				jQuery("#search_"+rec_id+" a.article_details").addClass("viewed_details");
			}
			if(rec_id == search.viewing){
				jQuery("#search_"+rec_id+" a.article_details").addClass("viewing_details");
			}
			if(classname)
				jQuery("#search_"+rec_id).addClass(classname);
		}else{	 
			var li = '<li id="search_t_'+rec_id+'" class="assoc_term_'+termid+'>'+'<div class="text"><small>'+search.res_ind+'.</small>&nbsp;<a href="#" class="article_details">'+title;
			if(year) li +=' ('+year+')';
			li += '</a></div></li>';

			jQuery("#results ul#top_list").append(li);

			var tl_ind = jQuery("#results ul#top_list li").index(jQuery('#search_t_'+rec_id));
			jQuery('#search_t_'+rec_id+' small').text((tl_ind+1)+'.');
			var first = jQuery("#results ul#top_list li").get(0);
			jQuery(first).addClass("first-li");

			if(classname)
				jQuery("#search_t_"+rec_id).addClass(classname);
			
		}
	}
	String.prototype.ucFirst = function () {
		return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
	};
	function prepare_td(data){
		td_str = '';
		i=0;
		var delim = ',';
		if(jQuery(data).get(0).tagName == 'creator') delim = ';';
		if(jQuery(data).get(0).tagName == 'identifier' || jQuery(data).get(0).tagName == 'relation') delim = '<br/>';
		jQuery("value",data).each(function(){
			i++;
			if(jQuery(this).text().search("http:\/\/")>=0)
				td_str += '<a href="'+jQuery(this).text()+'">'+jQuery(this).text()+'</a>';
			else
				td_str += jQuery(this).text();
			if(i<jQuery("value",data).length) td_str += delim+' ';
		});
		return td_str;
	}
	function render_details(xml){
		if(jQuery("#bottom .abstract").length==0)
			jQuery("#bottom").append('<div class="abstract"><h3>'+jQuery("record title value", xml).text()+'</h3></div>');
		else
			jQuery("#bottom .abstract").replaceWith('<div class="abstract"><h3>'+jQuery("record title value", xml).text()+'</h3></div>');
		var rec_id = jQuery("metadata record_id",xml).text();	
		var action_buttons = '<div class="actions"><ul>'+
					'<li id="search_detail_'+jQuery("metadata record_id", xml).text()+'">'+
					'<a id="go_to_item" class="article_forward" href="#"><button>Go to item</button></a></li>';
		if(jQuery("record[id="+rec_id+"]",search.marked).length==0)
			action_buttons +='<li id="search_mark_'+jQuery("metadata record_id", xml).text()+'">'+
					'<a id="mark_item" class="mark_article" href="#"><button>Add to marked list</button></a></li>';
		else
			action_buttons +='<li id="search_mark_'+jQuery("metadata record_id", xml).text()+'">'+
					'<p id="ml_added_mess">Added to marked list</p></li>';

		jQuery("#term_source_toggle").show();


		action_buttons+='</ul></div>';
		if(jQuery("#bottom .actions").length==0){
			jQuery("#bottom").append(jQuery(action_buttons));
		}else{
			jQuery("#bottom .actions").replaceWith(jQuery(action_buttons));
		}

		var desc = jQuery("record description",xml).text();
		if(desc.length && desc.length > search.desc_length){
			desc = desc.substring(0,search.desc_length);	
			var pat = /\s[\w,.]+\s*$/;
			desc = desc.substring(0,desc.search(pat))+"...";
		}
		jQuery("#bottom .abstract").append('<p>'+desc+'</p>');
		var table = '<table><tbody><tr>';
		if(jQuery("record creator",xml).length) table += '<th>Author(s)</th><td>'+prepare_td(jQuery("record creator",xml))+'</td>';
		if(jQuery("record date",xml).length) table += '<th>Date</th><td>'+prepare_td(jQuery("record date",xml))+'</td>';
		if(jQuery("record language",xml).length) table += '<th>Language</th><td>'+prepare_td(jQuery("record language",xml))+'</td>';
		if(jQuery("record type",xml).length) table += '<th>Type</th><td>'+prepare_td(jQuery("record type",xml))+'</td>';
		if(jQuery("record full_text value",xml).text().length) 
			table += '<th>Full Text</th><td>Yes</td>';
		else
			table += '<th>Full Text</th><td>No</td>';

		table += '</tr>';
		if(jQuery("record identifier",xml).length) table += '<tr><th>Identifier</th><td colspan="9">'+prepare_td(jQuery("record identifier",xml))+'</td></tr>';
		if(jQuery("record relation",xml).length) table += '<tr><th>Relation(s)</th><td colspan="9">'+prepare_td(jQuery("record relation",xml))+'</td></tr>';
		if(jQuery("record source",xml).length) table += '<tr><th>Source</th><td colspan="9">'+prepare_td(jQuery("record source",xml))+'</td></tr>';
		table +='</table>';

		jQuery("#bottom .abstract").append(table);
		jQuery("#go_to_item").closest("li").attr("id", "search_detail_"+jQuery("metadata record_id", xml).text());
		
		jQuery("#term_source_toggle button").live("click", function(){
			if(merlin.current_rs_terms){
				merlin.current_rs_terms=false;
				doc_terms(search.viewing);
				jQuery("#term_source_toggle button").text('View result-set terms');
			}else{
				merlin.current_rs_terms=true;
				merlin_request(false);
				jQuery("#term_source_toggle button").text('View document terms');
			}
			return false;
		});


		jQuery("#mark_item").click( function(){
			record_id = jQuery(this).closest("li").attr("id").split("search_mark_")[1];
//			if(debug) console.log("Marking: "+jQuery("metadata record_id", xml).text());
			add_to_marked_list(jQuery("metadata record_id", xml).text(),xml);
			return false;
		});

		render_viewed();
	}
	function doc_terms(record_id){
		var request = config.mer_dir+"/ajax/merlin_li.php";
		var search_data = jQuery("#search_form").serializeObject();
		var data = {recordid: record_id};
		if(merlin.term_format == 'cloud') data.as_cloud = 'on'; else data.as_cloud = undefined;

		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(terms){
				jQuery("#terms_cloud div.fieldset").html(terms);
				jQuery(".merlin_thes_term").remove();
				render_terms(jQuery("#terms_cloud div.fieldset"));
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}

		});
	/*
		jQuery("#terms_cloud div.fieldset").load(request, data, function(response, status, xhr) {
	//		if(debug) console.log(jQuery(this).html());

			if (status == "error") {
				var msg = "Sorry but there was an error: ";
				alert(msg + xhr.status + " " + xhr.statusText);	
			}else{
				render_terms(jQuery(this));
			}
		});
	*/
	}

	function get_marked_list(render){
		var request = config.mer_dir+"/ajax/marked_list.php";
		jQuery.ajax({
			type: "POST",
			url: request,
			async: false,
			success: function(xml){
				search.marked = jQuery("search",xml);
				if(render)
					render_marked();
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}
		});

	}
	function clear_marked_list(){
		var request = config.mer_dir+"/ajax/marked_list.php";
		var data ={clear:true};
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				search.marked = jQuery("search",xml);
				render_marked();
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}
		});

	}

	function add_to_marked_list(record_id, xml){
		var request = config.mer_dir+"/ajax/marked_list.php";
		var data = {};
		data.record_id = record_id;
		data.title = jQuery("record title", xml).text();
		data.rec_id = jQuery("metadata record_id", xml).text();
		var year = jQuery("record date",xml).text();
		year = year.substring(0,10);
		if(year.search('-00')>0)
			year = year.substring(0,year.search('-00'));
		data.year = year;
		data.logo = jQuery("metadata source_logo", xml).text();
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				search.marked = jQuery("search",xml);
//				if(debug) console.log("added to marked list...?");
				jQuery("#mark_item").replaceWith('<p id="ml_added_mess">Added to marked list</p>');
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}
		});
	}
	function render_marked(){
		if(jQuery("#search_form").length>0){
			search.search_form = jQuery("#search_form").clone();
			jQuery("#search_form").remove();
		}
		if(jQuery("record",search.marked).length==0){
		}
		if(jQuery("#form-content div.cont").length>0)
			jQuery("#form-content div.cont").html('<ul></ul>');
		else
			jQuery("#form-content").append('<div class="cont marked"><ul></ul></div>');
		if(jQuery("record",search.marked).length==0){
			jQuery("#form-content ul").replaceWith('<p>There are currently no marked items.</p>');
			return;
		}

		var ind = 1;
		jQuery("record",search.marked).each(function(){
			var title = jQuery(this).find("title").text();
			var rec_id = jQuery(this).find("rec_id").text();
			var year = jQuery(this).find("year").text();
			year = year.substring(0,10);
			if(year.search('-00')>0)
				year = year.substring(0,year.search('-00'));
			var logo = jQuery(this).find("logo").text();

			jQuery("#form-content ul").append('<li id="search_'+rec_id+'">'+
					'<div class="text"><small>'+ind+'.</small>&nbsp;<a href="#" class="article_details">'+title+' ('+year+')</a></div>'+
					'<div class="logo"><a href="#" class="article_forward"><img src="/images/small_'+logo+'"/></a></div></li>');
			ind++;

		});
		jQuery("#form-content div.marked li:first").addClass("first-li");
		jQuery("#form-content div.marked").append('<a style="margin-left: 10px; maring-bottom: 10px;" href="#" id="clear_marked_list">Clear marked list</a>');
		jQuery("#clear_marked_list").click(function(){
			clear_marked_list();
			return false;
		});
	}

	//var search = {};
	search.viewed = new Array();
	function add_to_viewed_stack(record_id,article,xml){
		if(jQuery(article).closest("ul").attr("id")=="main_list")
			jQuery(article).addClass("viewing_details").addClass("viewed_details");
		else
			jQuery("#search_"+record_id+" a").addClass("viewing_details");

		search.viewed[record_id] = xml;
		search.viewing = record_id;
		search.viewing_title = jQuery("title", xml).text();

	}
	function render_viewed(){
		if(!jQuery("div.rv").length)
			jQuery("div.actions").append('<div class="rv"></div>');
		
		jQuery("div.actions div.rv").html('<h4></h4><ul></ul>');
		for(i in search.viewed){
			if(i == search.viewing) continue;
			var title = jQuery("record title", search.viewed[i]).text();
			jQuery("div.actions div.rv ul").append('<li id="search_'+i+'"><a href="#" class="article_details">'+title+'</a></li>');
	/*&nbsp;<span class="remove_from_list" id="remove_'+i+'">x</span></li>');*/
		}
		if(jQuery("div.actions div.rv ul li").length > 0){ jQuery("div.actions div.rv h4").text('Recently viewed');}

		var heading_offset = parseFloat(jQuery("#bottom h1").css("margin-top").substr(0,(jQuery("#bottom h1").css("margin-top").length-2)));
		var bh =  jQuery("#bottom .abstract").height() - heading_offset;
		var bh2 = jQuery("#bottom .actions").height() - heading_offset;
		if(bh2 > bh)
			jQuery("#bottom").css({height: bh2});
		else
			jQuery("#bottom").css({height: bh});

	}
	/* MERLIN */
	/* 
	Two ways to request terms:
	 1) Directly (using the sort of joined query possible within lasso)
		terms = merlin_request(search_str);

	 2) Inderectly using a standard result format (in this case RSS) to obtain 
	 a list of identifiers which can be passed on to a stand alone merlin database
		xml = get_results_from_rss(search_str);
		merlin_request = build_merlin_request(xml);
		terms = merlin_request(merlin_request);
	*/

	var merlin = {};
	merlin.direct = false;
	merlin.current_rs_terms=true;
	merlin.term_format='cloud';
	var mcloud = {};
	mcloud.collapsed = true;
	mcloud.thes_vis = false;

	function get_results_from_rss(search_string){
		// Typical eprints rss request...
		// http://pubs.ulcc.ac.uk/cgi/search/simple?_action_export&output=RSS2&q=preservation
		// However still would need rss to return a reliable identifier (or at least one that is unique and held in merlin database)
		
		var data = jQuery("#search_form").serializeObject();
		data.date = data.daterange;
		var request = "/cgi/search/advanced/export_"+config.repo_id+"_RSS2_OpenSearch.xml";
		data.screen = "Public::EPrintSearch";
		data._action_export=1;
		data.output = "RSS2_OpenSearch";
		data.num_recs = '';
//		if(debug) console.log(request);
		jQuery.ajax({
			type: "GET",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				merlin.ids_str = build_ids_str(xml);
			},
			error: function (data, status, e){
				alert("rss request error: "+status);
			}
		});
	}

	function build_ids_str(xml){
		var ids_str = "";
		jQuery("item guid", xml).each(function(){
			var re = new RegExp(config.repo_url);
			var id = jQuery(this).text().replace(re,config.repo_oai_id);
			id = id.replace(/\/$/,"");
			ids_str+= id+"|";
		});
		ids_str = ids_str.substr(0,ids_str.length-1);
		return ids_str;
	}
	//m is a mystery param it will be different depending on whether merlin.direct is true or false...
	function merlin_request(m){
		var request = config.mer_dir+"/ajax/merlin_li.php";
		var data = {};
		var search_data = jQuery("#search_form").serializeObject();
		if(merlin.direct){
			data = {search_str: m};
		}else{
			if(merlin.ids_str.length==0){
				return false;
			}
			data = {ids_str: merlin.ids_str, search_str: search_data.q, as_cloud: search_data.as_cloud};

//			data = {temp_table: merlin.temp_table, search_str: search_data.kw};
			if(merlin.term_format == 'cloud') data.as_cloud = 'on'; else data.as_cloud = undefined;
		}

		jQuery("#terms_cloud div.fieldset").load(request, data, function(response, status, xhr) {
			if (status == "error") {
				var msg = "Sorry but there was an error: ";
				alert(msg + xhr.status + " " + xhr.statusText);	
			}else{
				render_terms(jQuery(this));
			}
		});
	}
	function render_terms(terms){

		if(merlin.term_format == 'cloud')
			f_but_text = "Show terms as list";
		else		
			f_but_text = "Show terms as cloud";

		if(merlin.current_rs_terms)
			d_but_text = "View document terms";
		else	
			d_but_text = "View result-set terms";
		var s = 's';
		if(t_data.t_num_term_docs == 1) s = '';
		var term_control = jQuery('<div id="termine_status_bar">'+
					'<p id="cloud_format"><span id="term_format_toggle"><button>'+f_but_text+'</button></span>'+
					'<span id="term_source_toggle"><button>'+d_but_text+'</button></span></p>'+
					'<p id="cloud_control"><span id="thes_terms_toggle"><button>Show thesaurus terms</button></span>'+
					'<span id="collapse_list_toggle"><button>Bring all to front</button></span></p>'+
					'<p id="termine_stats"><span id="termine_cloud_stats">Termine weight (t-score): '+
				'<span id="t_weight_disp"></span> (<span id="t_score_disp"></span>)</span>'+
				' ['+t_data.t_num_term_docs+' doc'+s+']</p>'+
				'</div>');

//		console.log(terms.contents());
//		console.log(t_data.t_num_terms);
		if(t_data.t_num_terms>0){ //results?

			if(merlin.term_format == 'cloud') { //as a cloud?
				
				jQuery(terms).find("ul").addClass("cloud");
				jQuery(terms).prepend('<h1><span>Termine terms</span></h1><h2><a href="#help_box_terms_cloud"><img alt="?" src="'+config.mer_dir+'/images/help.png"/></a></h2>');
				var l = jQuery("#terms").position().left+jQuery("#terms").width();
				jQuery("#terms_cloud .fieldset h2 a").css({position: 'absolute', top: jQuery("#terms").position().top-7, left: l-20});
				jQuery(terms).find("h2 a").fancyZoom({directory: config.mer_dir+'/images', width: 600});
				jQuery(terms).append('<div id="slider"></div>');
				jQuery(terms).append(term_control);

				//if(debug) console.log("min: "+t_data.t_min+", max: "+t_data.t_max);
				jQuery('#slider').slider({ orientation: 'vertical', 
						min: t_data.t_min,
						max: t_data.t_max,
						value: t_data.t_slider_default,
						change: function(event,ui){
								t_slide();
							} 
						});

				mcloud.top_offset = 60;
				jQuery(".center_div").css({position: 'relative', top: "+"+mcloud.top_offset+"px"});

				var column_height = jQuery("#form-content").height();
				var column_width = jQuery("#terms").width()-5;
				var slider_offset = jQuery("#terms div.fieldset ul").position().top - jQuery("#terms div.fieldset").position().top;
				jQuery("#terms div.fieldset").css({height: column_height+"px", width: column_width+"px"});
				jQuery("#termine_status_bar").width(column_width+1);
				var status_offset = jQuery("#termine_status_bar").height()+15;
				
				jQuery("#cloud").css({height: (column_height-status_offset*2-mcloud.top_offset)+"px", width: (column_width-jQuery("#slider").width()-13)+"px"});
				jQuery("div.center_div").css({width: (jQuery("#cloud").width()-10)+"px"});
				jQuery("#slider").css({height: (column_height-status_offset)+"px", left: '1px'});
				var value = t_data.t_max - t_data.t_slider_default +t_data.t_min;
				display_t_weight(value);
				if(jQuery(".merlin_thes_term").length)
					thesaurus_fetch();	
				jQuery("#thes_terms_toggle button").click(function(){
					if(!mcloud.thes_vis){
						jQuery(this).text("Hide thesaurus terms");
						show_thes_terms();
					}else{
						jQuery(this).text("Show thesaurus terms");
						hide_thes_terms();
					}
					return false;
				});             
				jQuery("#collapse_list_toggle button").click(function(){
					if(mcloud.collapsed){
						jQuery(this).text("Collapse cloud");
						make_list_avoid(jQuery(".center_div ul#cloud"), mcloud.merlin_search_term, "first");
					}else{
						jQuery(this).text("Bring all to front");
						collapse_list();
					}
					return false;
				});       
				set_option_boxes();

			}else{
				jQuery(".merlin_thes_term").remove();
				jQuery("#terms div.fieldset").prepend('<h1><span>Termine terms</span></h1><h2><a href="#help_box_terms_list"><img alt="?" src="images/help.png"/></a></h2>');

				var l = jQuery("#terms").position().left+jQuery("#terms").width();
				jQuery("#terms_cloud .fieldset h2 a").css({position: 'absolute', top: jQuery("#terms").position().top-7, left: l-20});
				jQuery("#terms h2 a").fancyZoom({directory: config.mer_dir+'/images', width: 600});
				jQuery("#terms div.fieldset div").addClass("normal_list");
				jQuery("#terms div.fieldset").append(term_control);

				jQuery("#termine_cloud_stats").hide();


				jQuery("#terms div.fieldset div li").removeClass("hidden").attr("style","").each(function(){
					var value = jQuery(this).attr("t_weight");
					var weight_prop = (value/t_data.t_max)*100;
					weight_prop  = Math.round(weight_prop);
					prop_image(weight_prop);
					jQuery(this).append('&nbsp;<span class="termine_weight"><img src="'+prop_image(weight_prop)+'" alt="'+weight_prop+'%" title="'+weight_prop+'%"/></span>');
				});
				set_option_boxes();

				var status_offset = jQuery("#termine_status_bar").height()-15;	
				var column_height = jQuery("#form-content").height() - jQuery("#terms h2").height();
				jQuery("#terms div.fieldset div.center_div").css({width: jQuery("#terms").width()-7+'px', height: column_height-status_offset+"px"});

				var column_width = jQuery("#terms").width()-5;
				jQuery("#termine_status_bar").width(column_width+1);


				var status_pos = jQuery(".normal_list").position().top + jQuery(".normal_list").height();
//				if(debug) console.log("status_pos : "+status_pos);
				jQuery("#termine_status_bar").css({position: 'absolute', top: status_pos});
				jQuery("#thes_terms_toggle button").hide();
			}
				
			if(search.viewing){
				jQuery("#term_source_toggle").show();
			}
			jQuery('#term_format_toggle button').click(function(){
				if(merlin.term_format == 'cloud')
					merlin.term_format = 'list';
				else
					merlin.term_format = 'cloud';
							
				if(merlin.current_rs_terms)
					merlin_request();
				else
					doc_terms(search.viewing);	
			});
			var button_space_width = (jQuery("#termine_status_bar").width()-20)/2
			jQuery("#cloud_format").width(button_space_width+10);
			jQuery("#cloud_control").width(button_space_width-10);

		}else{
			render_no_terms();
		}
	}
	function prop_image(weight_prop){
		var w = weight_prop/10;
		w = Math.round(w)*10;
		return "/merlin-ui/images/"+w+"pc.png";
	}
	function thesaurus_fetch(){
		
		var request = config.mer_dir+"/ajax/hilt.php";
		var data = {term: merlin.search_string};
//		if(debug) console.log(request+" "+dump(data));
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(hilt_skos){
				merlin.thes_obj = hilt_skos;
				thesaurus_concepts();
				place_thes_terms();
			},
			error: function (data, status, e){
	//                        alert("Could get no sense from : data**: "+data+" status: "+status+" e: "+e);
//				if(debug) console.log("Could get no sense from hilt\ndata: "+data+" status: "+status+" e: "+e);
				place_thes_terms();
			}
		});
		
	}
	function thesaurus_concepts(){
	//	if(debug) console.log(jQuery("[nodeName=skos:Concept]", merlin.thes_obj).length);	
		if(jQuery("[nodeName=skos:Concept]", merlin.thes_obj).length>0){
			var concepts = jQuery('<ul></ul>');
			jQuery("[nodeName=skos:Concept]", merlin.thes_obj).each(function(ind){
				var braoder_id = 0;
				var broader_ids = [];
				var narrower_id = 0;
				var narrower_ids = [];
				var related_id = 0;	
				var related_ids = [];
				if(jQuery(this).find("[nodeName=skos:broader]").length){
					jQuery(this).find("[nodeName=skos:broader]").each(function(){
						broader_ids.push(jQuery(this).attr("rdf:resource").split("#")[1]);
					});
				}else{
					broader_ids = [0];
				}
				if(jQuery(this).find("[nodeName=skos:narrower]").length){
					jQuery(this).find("[nodeName=skos:narrower]").each(function(){
						narrower_ids.push(jQuery(this).attr("rdf:resource").split("#")[1]);
					});
				}else{
					narrower_ids = [0];
				}
				if(jQuery(this).find("[nodeName=skos:related]").length){
					jQuery(this).find("[nodeName=skos:related]").each(function(){
						related_ids.push(jQuery(this).attr("rdf:resource").split("#")[1]);
					});
				}else{
					related_ids = [0];
				}

				var rels = "['"+broader_ids.join(':')+"','"+narrower_ids.join(':')+"','"+related_ids.join(':')+"']";
				jQuery(concepts).append('<li rel="'+rels+'">'+jQuery(this).find("[nodeName=skos:prefLabel]").text().toLowerCase()+'</li>');
			});
		}else{
			var concepts = "<small>No associated concepts for \""+merlin.search_string+"\"</small>";	
			
		}

		mcloud.thes_left_tip_init =  '<div class="merlin_tooltip" id="thes_left_tip_cont"><span id="thes_left_tip_init">Click on \"Show thesaurus terms\" in the blue bar below to browse thesaurus.</span></div>';
		mcloud.thes_left_tip_intro = '<span id="thes_left_tip_intro"><h1>Concepts associated with "'+merlin.search_string+'"</h1><p>Use your mouse-wheel or up and down cursor keys to scroll though the list of concepts associated with "'+merlin.search_string+'".</p><p>Click to reveal related, broader and narrower terms. If you are browsing a concept (ie it goes <span style="color: #609060;">green</span>) you can click on it to center the search on that term.</p></span>';

		jQuery(".thes_left").html(jQuery(concepts)).after(mcloud.thes_left_tip_init);

		jQuery(".thes_left").tooltip({
			position: "bottom center",
			tipClass: "merlin_tooltip",
			offset: [0,50],
			relative: true
		});
	/*
			onBeforeShow: function(){
				if (this.getTrigger().attr('title') != '') {
					this.getTip().text( this.getTrigger().attr('title') );
					this.cancelDefault = true;
				}
			}

			onBeforeShow: function(){
				mcloud.thes_left_tip = this.getTip();
			}
	*/
		jQuery(".thes_left").click(function(){
			if(jQuery(this).css("opacity")<0.5) return;

			jQuery(".thes_left ul li").removeClass("concept");
			jQuery(".thes_left li").each(function(ind){
				if(isScrolledIntoView(jQuery(this),jQuery(".thes_left"))){
					jQuery(this).addClass("concept");
					mcloud.current_concept = jQuery(this).text();
					jQuery(this).unbind("click");
					jQuery(this).siblings("li").unbind("click");
					jQuery(this).click(function(){
						jQuery("#search_form input[name=kw]").val(jQuery(this).text());
						jQuery("#search_form").trigger("submit");
						jQuery(".merlin_tooltip").remove();
						return false;
					});
					thesaurus_relations(jQuery(this).attr("rel"));
					return false;
				}
			});
		});
	}

	function thesaurus_relations(ids){

		eval("var ids_arr = "+ids);
		jQuery(".thes_down").html("");
		jQuery(".thes_up").html("");
		jQuery(".thes_right").html("");
		if(ids_arr[0]){
			//broader
			expand_relation(ids_arr[0],"up");
		}
		if(ids_arr[1]){
			//narrower
			expand_relation(ids_arr[1],"down");
		}
		if(ids_arr[2]){
			//related
			expand_relation(ids_arr[2],"right", true);
		}

	}
	function expand_relation(ids, where, and_place){
		var request = config.mer_dir+"/ajax/hilt.php";
		var data = {ids: ids};
		
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(hilt_skos){

				if(jQuery("[nodeName=skos:Concept]", hilt_skos).length>0){
					var concepts = jQuery('<ul></ul>');
					jQuery("[nodeName=skos:Concept]", hilt_skos).each(function(ind){
						jQuery(concepts).append('<li>'+jQuery(this).find("[nodeName=skos:prefLabel]").text().toLowerCase()+'</li>');

					});
				}else{
					var concepts = "";

				}
				jQuery(".thes_"+where).html(jQuery(concepts));
				jQuery(".thes_"+where).click(function(){
					jQuery(".thes_"+where+" li").each(function(ind){
						if(isScrolledIntoView(jQuery(this),jQuery(".thes_"+where))){
							jQuery("#search_form input[name=kw]").val(jQuery(this).text());
							jQuery("#search_form").trigger("submit");
							return false;
						}
					});
				});

				if(and_place)
					place_thes_terms(true);


				mcloud.thes_right_tip_intro = '<div class="merlin_tooltip" id="thes_right_tip_cont"><span id="thes_right_tip_intro"><h1>Terms related to "'+mcloud.current_concept+'"</h1><p>Use your mouse-wheel or up and down cursor keys to scroll though the list of related terms.</p><p>Click to center the search on that term.</p></span></div>';
				mcloud.thes_up_tip_intro = '<div class="merlin_tooltip" id="thes_up_tip_cont"><span id="thes_up_tip_intro"><h1>Broader term for "'+mcloud.current_concept+'"</h1><p>Click to to center the search on that term.</p></span></div>';
				mcloud.thes_down_tip_intro = '<div class="merlin_tooltip" id="thes_down_tip_cont"><span id="thes_down_tip_intro"><h1>Narrower terms for "'+mcloud.current_concept+'"</h1><p>Use your mouse-wheel or up and down cursor keys to scroll though the list of narrower terms.</p><p>Click to center the search on that term.</p></span></div>';
				if(jQuery("#thes_"+where+"_tip_cont").length){
					jQuery("#thes_"+where+"_tip_cont").empty().html(jQuery(eval("mcloud.thes_"+where+"_tip_intro")).find("span"));
				}else{

					jQuery(".thes_"+where).after(eval("mcloud.thes_"+where+"_tip_intro"));
				}

				jQuery(".thes_"+where).tooltip({
					position: "bottom center",
					tipClass: "merlin_tooltip",
					offset: [0,50],
					relative: true
				});

			},
			error: function (data, status, e){
				alert("get term records error: data: "+data+" status: "+status+" e: "+e);
			}
		});
	}

	function isScrolledIntoView(elem, container)
	{
		if(container == undefined)
			container = window;
		
		var docViewTop = jQuery(container).offset().top;
		var docViewBottom = docViewTop + jQuery(container).height();

		var elemTop = jQuery(elem).offset().top;
		var elemBottom = elemTop + jQuery(elem).height();

		if((docViewTop <= elemTop) && (docViewBottom >= elemBottom)){
	/*		console.log(jQuery(elem).text()+" container height: "+jQuery(container).css("height"));
			console.log("top: "+docViewTop+" bottom: "+docViewBottom);
			console.log("e-top: "+elemTop+" e-bottom: "+elemBottom);*/
			return true;
		}else{
			return false;
		}
	}

	/*************** deprecated! ***************/
	function move_list(li,prev_left,prev_top){
		if(jQuery(li).length==0)
			return false;

		var left = jQuery(li).position().left-prev_left;
		lsign="-";
		if(left < 0) lsign="+";
		abs_left = Math.abs(parseInt(left));
		var top = jQuery(li).position().top-prev_top;
		tsign="-";
		if(top < 0) tsign="+";
		abs_top = Math.abs(parseInt(top));

		if((abs_left+jQuery(li).width()+merlin.l_bound)>merlin.r_bound){
			abs_left = 3;
			abs_top -=merlin.top_line_height;
			merlin.top_line_height=0;
		}
		if(jQuery(li).find("a").height()>merlin.top_line_height){
			merlin.top_line_height=jQuery(li).find("a").height();
		}
		//margin-left
		if(abs_left)
			abs_left+=merlin.m_left;
		jQuery(li).css({left: lsign+abs_left+"px",
			   top: tsign+abs_top+"px"});

			merlin.tags_moved++;
			prev_left = jQuery(li).position().left+jQuery(li).width();
			prev_top = jQuery(li).position().top;

			if(!jQuery(li).next("li").length){

				set_option_boxes();
				var column_height = jQuery("#form-content").height();
				var column_width = jQuery("#terms").width()-5;
				var slider_offset = jQuery("#terms div.fieldset ul").position().top - jQuery("#terms div.fieldset").position().top;
				jQuery("#terms div.fieldset").css({height: column_height+"px", width: column_width+"px"});
				jQuery("#termine_status_bar").width(column_width+1);

				var status_offset = jQuery("#termine_status_bar").height();

				jQuery("#terms div.fieldset ul").css({height: (column_height-slider_offset-status_offset+7)+"px", width: (column_width-jQuery("#slider").width()-3)+"px"});
				jQuery("#slider").css({height: (column_height-slider_offset-status_offset+7)+"px", left: '1px'});
				var value = t_data.t_max - t_data.t_slider_default +t_data.t_min;
				display_t_weight(value);
			}else{
				move_list(jQuery(li).next("li"),prev_left,prev_top);
			}		

	}
	/************************************************/
	function dump(obj) {    
		var out = '';
		for (var i in obj) {
			out += i + ": " + obj[i] + "\n";
		}
		return out;
	}

	var t_data = {};
	function display_t_weight(value){
		var weight_prop = (value/t_data.t_max)*100;
		weight_prop  = Math.round(weight_prop);
		jQuery("#t_weight_disp").html(weight_prop+"%");
		var t_score = Math.round(value);
		jQuery("#t_score_disp").html(t_score);
	}
	function t_slide(){
		var value = jQuery('#slider').slider('option', 'value');
		value = t_data.t_max - value +t_data.t_min;
		display_t_weight(value);
		jQuery("#terms_cloud li").each(function(){
			if(jQuery(this).attr("t_weight") < value){
				jQuery(this).addClass("hidden");
				jQuery(this).find("a").unbind("click");
				jQuery(this).find("a").click(function(){ return false; });
			}else{
				jQuery(this).removeClass("hidden");
				set_option_box(jQuery(this));
			}
		});
	}

	function get_resultset_term_records(termid){
		var request = config.mer_dir+"/ajax/merlin_li.php";
	//	var data = {termid: termid, search_string: merlin.search_string};
		var data = {termid: termid, output_format: "xml"};
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				merlin.terms = xml;
				jQuery("term", merlin.terms).each(function(){
					var rec_id = jQuery(this).find("record_id").text();
					var title = jQuery(this).find("title").text();
					//add record to top_list
					if(jQuery("#top_list #search_"+rec_id).length==0)
						render_result_row(jQuery(this),termid,"term_refined");
					else
						jQuery("#top_list #search_"+rec_id).fadeTo('slow',0.5, function(){ jQuery(this).fadeTo('fast', 1);}).addClass("assoc_term_"+termid);
					
				});
				//hilight the term
				jQuery("#terms_cloud li a#term_tag_"+termid).addClass("term_refined");
				//tone down the results main-list
				jQuery("#results-content ul#main_list li").fadeTo('slow',0.3);
			},
			error: function (data, status, e){
				alert("get term records error: "+status);
			}
		});
	}
	function get_term_records(termid){
		var request = config.mer_dir+"/ajax/merlin_li.php";
		var data = {termid: termid, output_format: "xml"};
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				merlin.terms = xml;
				jQuery("term", merlin.terms).each(function(){
					var rec_id = jQuery(this).find("record_id").text();
					var title = jQuery(this).find("title").text();
					//add record to top_list
					if(jQuery("#top_list #search_"+rec_id).length==0)
						render_result_row(jQuery(this),termid,"term_unrefined");
					else
						jQuery("#top_list #search_"+rec_id).fadeTo('slow',0.5, function(){ jQuery(this).fadeTo('fast', 1);}).addClass("assoc_term_"+termid);
					
				});
				//hilight the term
				jQuery("#terms_cloud li a#term_tag_"+termid).addClass("term_unrefined");
				//tone down the results main-list
				jQuery("#results-content ul#main_list li").fadeTo('slow',0.3);
			},
			error: function (data, status, e){
				alert("get term records error: "+status);
			}
		});
	}

	function set_option_boxes(){
		jQuery("#terms ul li").not("#merlin_search_string").each(function(){
			set_option_box(jQuery(this));
		});
		jQuery("#terms_cloud li#merlin_search_string").click(function(){return false;});
	}
	function set_option_box(li){
		jQuery(li).find("a").click(function(){
			if(jQuery(this).closest("li").hasClass("hidden")){ return false; }
			if(jQuery(this).hasClass("term_refined")){
				jQuery(this).removeClass("term_refined");
				var termid = jQuery(this).attr("id").split("term_tag_")[1];
				var rem_recs = jQuery("#top_list li.assoc_term_"+termid);
				jQuery(rem_recs).each(function(){
					jQuery(this).removeClass("assoc_term_"+termid);
					if(jQuery(this).attr("class").search("assoc_term")==-1)
						jQuery(this).fadeOut().remove();
				});
				jQuery("#top_list li").each(function(){
					var tl_ind = jQuery("#results ul#top_list li").index(jQuery(this));
					jQuery(this).find('small').text((tl_ind+1)+'.');	
				});
				var first = jQuery("#results ul#top_list li").get(0);
				jQuery(first).addClass("first-li");
				if(jQuery("#terms .term_refined").length==0)
					jQuery("#main_list li").fadeTo('slow',1);
				return false;
			}
			if(jQuery(this).hasClass("term_unrefined")){
				jQuery(this).removeClass("term_unrefined");
				var termid = jQuery(this).attr("id").split("term_tag_")[1];
				var rem_recs = jQuery("#top_list li.assoc_term_"+termid);
				jQuery(rem_recs).each(function(){
					jQuery(this).removeClass("assoc_term_"+termid);
					if(jQuery(this).attr("class").search("assoc_term")==-1)
						jQuery(this).fadeOut().remove();
				});
				jQuery("#top_list li").each(function(){
					var tl_ind = jQuery("#results ul#top_list li").index(jQuery(this));
					jQuery(this).find('small').text((tl_ind+1)+'.');	
				});
				var first = jQuery("#results ul#top_list li").get(0);
				jQuery(first).addClass("first-li");
				if(jQuery("#terms .term_refined").length==0)
					jQuery("#main_list li").fadeTo('slow',1);
				return false;
			}

			jQuery("div.merlin_options_box").fadeOut();
			if(jQuery(this).closest("li").find("div.merlin_options_box").length){
				jQuery(this).closest("li").find("div.merlin_options_box").fadeIn();
				jQuery(this).closest("li").find("div.merlin_options_box").mouseleave(function(){
					jQuery(this).fadeOut();
				});
			}else{
				render_option_box(jQuery(this));
			}
			return false;
		});
	}
	/* Options
		1/ search for term within result set -> this will essentially show you where the term came from within the result set
		2/ search for term within the term database -> This will find all the records that are associated with the term
		3/ search for term within the lasso databse -> the in_metadata flag may be of use here...? maybe not though
	*/
	function render_option_box(link){
		var termid = jQuery(link).attr("id").split("term_tag_")[1];
		var this_term = jQuery(link).text();
		var div = jQuery('<div class="merlin_option_box" id="merlin_term_opt_'+termid+'"><h2><a href="#"><img src="fz/jquery/images/closebox.png" alt="?"/></a></h2><ul></ul></div>');
		
		jQuery(div).append('<li class="first-li rs_search"><a href="#" id="rs_'+termid+'">Show me the results for "'+merlin.search_string+'" that contain "'+this_term+'"</a></li>');
		jQuery(div).append('<li class="mdb_search"><a href="#" id="mdb_'+termid+'">Expand search to all records that contain the term "'+this_term+'"</a></li>');
		jQuery(div).append('<li class="bs_search"><a href="#" id="bs_'+termid+'">Change search to use the term "'+this_term+'"</a></li>');

		jQuery("body").append(div);

		if(jQuery(link).closest("div").hasClass("normal_list"))
			var top = jQuery("#terms").position().top+jQuery(link).closest("li").position().top+jQuery(link).closest("li").height();
		else
			var top = jQuery("#terms").position().top+mcloud.top_offset+jQuery(link).closest("li").position().top+jQuery(link).closest("li").height();

		var left = jQuery("#terms").position().left+jQuery(link).closest("li").position().left;
		var width = jQuery(link).width();
		var height = jQuery(link).height();

		if(jQuery.browser.msie && jQuery.browser.version.substr(0,1)<7){ top=0;jQuery(div).css({width: '300px'}); }

		if(jQuery(link).parents("#actual_list").length){
			jQuery(div).css({"top": (top+(height*0.75)),"left": (left+(width*0.5))});
		}else
			jQuery(div).css({"top": (top+(height*0.75)),"left": (left+(width*0.75))});

		jQuery(div).fadeIn();
		jQuery(".merlin_option_box h2 a img").click(function(){
			jQuery(div).hide();
		});
		jQuery(".rs_search").click(function(){
			jQuery(this).append('&nbsp; <img src="'+config.mer_dir+'/images/ajax-loader-small.gif"/>');
			get_resultset_term_records(termid);
			jQuery(div).fadeOut('fast');
			return false;
		});
		jQuery(".mdb_search").click(function(){
			get_term_records(termid);
			return false;
		});
		jQuery(".bs_search").click(function(){
			jQuery("#search_form input[name=kw]").val(this_term);
			jQuery("#search_form").trigger("submit");
			return false;
		});


		jQuery(div).mouseleave(function(){
			jQuery(this).hide();
		});
	}
	function update_search_string(){
		jQuery(".search_switch").click(function(){
			jQuery("#search_string").attr("name", jQuery(this).attr("id"));
			return false;
		});
	}
	function get_search_history(render){
		var request = config.mer_dir+"/ajax/search-history.php";
		jQuery.ajax({
			type: "POST",
			url: request,
			async: false,
			success: function(xml){
				search.searches = jQuery("search",xml);
				if(jQuery("#search_form").length>0){
					search.search_form = jQuery("#search_form").clone();
					jQuery("#search_form").remove();
				}
				if(render)
					render_search_history();
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}
		});

	}
	function render_search_history(){

		if(jQuery("#form-content div.cont").length>0)
			jQuery("#form-content div.cont").html('<ul></ul>');
		else
			jQuery("#form-content").append('<div class="cont"><ul></ul></div>');

		if(jQuery("search", search.searches).length){
			jQuery("search", search.searches).each(function(){
				jQuery("#form-content ul").append('<li>'+jQuery(this).find("index").text()+': '+
					'<a href="#" id="re_search_'+jQuery(this).find("index").text()+'" class="re_search">'+jQuery(this).find("search_title").text()+'</a>'+
					' ('+jQuery(this).find("num_results").text()+')</li>');
			});
			jQuery(".re_search").click(function(){
				jQuery("#MainNav a").removeClass("active");
				jQuery("#search").addClass("active");
					
				var search_id = jQuery(this).attr("id").split("re_search_")[1];
				re_search(search_id);
			});
		}else{
			jQuery("#form-content div.cont").html('<p class="search_message">'+jQuery("message", search.searches).text()+'</p>');
		}
	}
	function re_search(search_id){
		
		jQuery(search.search_form).find("input[name=kw]").val(jQuery("search[id="+search_id+"]", search.searches).find("all_fields").text());
		jQuery(search.search_form).find("select[name=daterange]").val(jQuery("search[id="+search_id+"]", search.searches).find("daterange").text());
		var sources = [];
		jQuery("search[id="+search_id+"]", search.searches).find("collection").each(function(){
			sources.push(jQuery(this).text());
		});
		jQuery(search.search_form).find("select[name='source[]']").val(sources);
		var types = [];
		jQuery("search[id="+search_id+"]", search.searches).find("material_type").each(function(){
			types.push(jQuery(this).text());
		});
		jQuery(search.search_form).find("select[name='type[]']").val(types);
		jQuery(search.search_form).find("input[name=fullFilter]").val(jQuery("search[id="+search_id+"]", search.searches).find("FullText").text());
		jQuery(search.search_form).find("input[name=peerFilter]").val(jQuery("search[id="+search_id+"]", search.searches).find("PeerReviewed").text());
		jQuery("#form-content ul").remove();
		jQuery("#form-content").append(jQuery(search.search_form));
		jQuery("#search_form").submit(function(){
			jQuery("#terms_cloud").html('<div class="fieldset term_loader"><img src="/images/ajax-loader.gif"/></div>');
			jQuery("#terms_cloud .term_loader").width(jQuery("#terms").width()-10);
			jQuery("#terms_cloud .term_loader").height(jQuery("#form-content").height());
			jQuery("#terms ul").html('');
			jQuery("#results").html('');
			do_search(jQuery(this));
			return false;
		});	
		jQuery("#search_form").trigger("submit");
	}
	function browse(index,id,page){
		var request = config.mer_dir+"/ajax/browse.php";
		var data = {};
		if(index != undefined) data.index = index;
		if(id != undefined) data.id = id;
		if(page != undefined) data.page = page;
		if(jQuery("fieldset#browse select[name=num_recs]").length) data.num_recs = jQuery("fieldset#search select[name=num_recs]").val();
		if(jQuery("fieldset#browse input[name=fullFilter]:checked").length) data.fullFilter = jQuery("fieldset#filters input[name=fullFilter]").val();
		if(jQuery("fieldset#browse input[name=peerFilter]:checked").length) data.peerFilter = jQuery("fieldset#filters input[name=peerFilter]").val();
	//	if(debug) console.log(request+" "+dump(data));
		jQuery.ajax({
			type: "POST",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				search.browse_tree = jQuery("search",xml);
				render_browse();
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}
		});
	}
	function render_browse(){
		if(jQuery("#search_form").length>0){
			search.search_form = jQuery("#search_form").clone();
			jQuery("#search_form").remove();
		}

		if(jQuery("record",search.browse_tree).length==0){
			if(jQuery("#form-content div.cont").length>0)
				jQuery("#form-content div.cont").html('');
			else
				jQuery("#form-content").append('<div class="cont"></div>');

			if(jQuery("#form-content ul").length>0 && jQuery("browse_item", search.browse_tree).length){
				jQuery("#form-content ul").html('');
			}else{
				var form = '<fieldset id="browse">'+
					'<label class="nexto">Number of results to show: </label>'+
					'<select name="num_recs">'+
						'<option>5</option>'+
						'<option>10</option>'+
						'<option selected="selected">20</option>'+
						'<option>50</option>'+
					'</select>'+
					'<br style="clear: both;"/>'+
					'<label for="fullText">Full-text records only</label>'+
					'<input type="checkbox" class="checkBox" name="fullFilter" id="fullText" value="y"/>'+
					'<br style="clear: both;"/>'+
					'<label for="peerR">Peer-reviewed records only</label>'+
					'<input type="checkbox" class="checkBox" name="peerFilter" id="peerR" value="y"/>'+
					'<br style="clear: both;"/>'+
				'</fieldset>';
				jQuery("#form-content div.cont").append(form);
				jQuery("#form-content div.cont").append('<ul></ul>');
			}
		}
		var index = false;
		if(jQuery("index", search.browse_tree).length>0){
			index = jQuery("index", search.browse_tree).text();
		}

		jQuery("browse_item", search.browse_tree).each(function(){
			var label = jQuery(this).find("id").text();
			if(jQuery(this).find("label").length)
				label = jQuery(this).find("label").text();
			if(index)
				jQuery("#form-content ul").append('<li><a href="#" id="id_'+jQuery(this).find("id").text()+'" class="browse result">'+label+'</a></li>');
			else
				jQuery("#form-content ul").append('<li><a href="#" id="index_'+jQuery(this).find("id").text()+'" class="browse">'+label+'</a></li>');
		});

		if(jQuery("num_records",search.browse_tree).length){
			search.results = search.browse_tree;
			jQuery("#results").html('<div class="fieldset" id="results-content"><h1><span></span></h1><h2><a href="#help_box_results"><img alt="?" src="images/help.png"/></a></h2><div id="res_paging"></div><div id="result_list"><div><ul id="top_list"></ul></div><ul id="main_list"></ul></div></div>');

			jQuery('#results-content h2 a').fancyZoom({directory: config.mer_dir+'/images', width: 600});
			render_results();
		}else{
			jQuery(".browse").click(function(){
				jQuery("#MainNav a").removeClass("active");
				jQuery("#browse").addClass("active");
				if(!jQuery(this).hasClass("result"))
					index = jQuery(this).attr("id").split("index_")[1];
				else
					var id = jQuery(this).attr("id").split("id_")[1];
				browse(index,id);
			});
		}
		jQuery("#form-content").height(jQuery("#terms .fieldset").height());
		jQuery("#form-content ul").height(jQuery("#terms .fieldset").height() - jQuery("fieldset#browse").height()- jQuery(".fieldset h2").height() -25);

	}
	function embed_feedback(){
	}

	function do_search(form,from){

		var data = jQuery(form).serializeObject();
		if(from) data.from = from;
		if(data.daterange=="dr"){
			data.daterange = data.date_from+"-"+data.date_to;
		}
		data.date = data.daterange;
		var request = "/cgi/search/advanced/export_"+config.repo_id+"_RSS2_OpenSearch.xml";
		data.screen = "Public::EPrintSearch";
		data._action_export=1;
		data.output = "RSS2_OpenSearch";
		if(debug){
			console.log("Requesting terms: "+request+" "+dump(data));
			console.log("Search object: "+dump(search));
		}


		jQuery.ajax({
			type: "GET",
			url: request,
			data: data,
			async: false,
			success: function(xml){
				search.results = jQuery("rss",xml);
				//Merlin
				var search_string = data.q;
				merlin.search_string = search_string;
				if(jQuery("item", search.results).length == 0){
					render_no_results();
				}else{
//					if(debug) console.log(jQuery("item",search.results).length);
					render_results();
					if(jQuery("#terms ul").children().length==0){
						if(merlin.direct){
							merlin_request(search_string);
						}else{
							//search again without a result limit (this will be used for our merlin request)
							get_results_from_rss(search_string);
							merlin_request(false);
						}
					}
				}
			},
			error: function (data, status, e){
				alert("Error from xml request: "+status);
			}
		});
	}


	/******* NEW CLOUD CODE ******/
	function show_thes_terms(){

		jQuery(".merlin_thes_term").fadeTo("slow",1).css({'z-index': 10});
		jQuery("#collapse_list_toggle").fadeIn("slow");
		jQuery("#cloud a").fadeTo("slow",0.3).closest("li").css({'z-index': 5});;
		mcloud.thes_vis = true;
		
		jQuery("#thes_left_tip_cont #thes_left_tip_init").empty().html(mcloud.thes_left_tip_intro);
		jQuery("#thes_right_tip_cont").empty().html(jQuery(mcloud.thes_right_tip_intro).find("span"));
		jQuery("#thes_up_tip_cont").empty().html(jQuery(mcloud.thes_up_tip_intro).find("span"));
		jQuery("#thes_down_tip_cont").empty().html(jQuery(mcloud.thes_down_tip_intro).find("span"));

	}
	function hide_thes_terms(){
		jQuery(".merlin_thes_term").fadeTo("slow",0.3).css({'z-index': 5});
		jQuery("#collapse_list_toggle").fadeOut("slow");
		jQuery("#cloud a").fadeTo("slow",1).closest("li").css({'z-index': 10});;
		mcloud.thes_vis = false;
		if(!mcloud.collapsed){
			jQuery("#collapse_list_toggle button").trigger("click");
		}
		jQuery("#thes_left_tip_intro").empty().html(jQuery(mcloud.thes_left_tip_init).find("span"));
		jQuery("#thes_right_tip_intro").empty().html(jQuery(mcloud.thes_left_tip_init).find("span"));
		jQuery("#thes_up_tip_intro").empty().html(jQuery(mcloud.thes_left_tip_init).find("span"));
		jQuery("#thes_down_tip_intro").empty().html(jQuery(mcloud.thes_left_tip_init).find("span"));

	}
	function collapse_list(){
		jQuery(".thes_down").animate(
				{top: "-="+mcloud.thes_down_dist+'px'}, 
				"fast", 
				function() {
				}
		);
		jQuery(".thes_up").animate(
				{top: "+="+mcloud.thes_up_dist+'px'}, 
				"fast", 
				function() {
				}
		);
		jQuery(".move").each(function(){
			var cnt = jQuery(this).children("ul").contents();
			jQuery(this).replaceWith(cnt);
		});

		mcloud.collapsed = true;
		if(mcloud.thes_vis)
		      jQuery("#cloud a").fadeTo("slow",0.3);
	}
	function place_term(selector, left, left_offset, top, top_offset){

		var cdw = jQuery("#actual_list").width();
		var cdh = jQuery("#actual_list").height();
		if(cdh<200) {jQuery("#actual_list").height(200); cdh=200;}
		
		var w = jQuery(selector).width();
		var h = jQuery(selector).height();
		var pos_l = (cdw*left)-(w*left_offset);
		var pos_t = (cdh*top)-(h*top_offset);
		var pos_b = pos_t + h;
		var pos_r = pos_l + w;

		jQuery(selector).css({left: pos_l, top: pos_t});
		
		selector = selector.replace(".","");
		selector = selector.replace("#","");
		eval("mcloud."+selector+" = {l: pos_l, t: pos_t, b: pos_b, r: pos_r};");

	}
	function rejig_avoid_coords(rj_selectors){
		for(var i=0; i<rj_selectors.length; i++){
			//lefter?
			if(jQuery(rj_selectors[i]).position().left < mcloud.merlin_search_term['l']){
				mcloud.merlin_search_term['l'] = jQuery(rj_selectors[i]).position().left;
			}
			//righter?
			if((jQuery(rj_selectors[i]).position().left+jQuery(rj_selectors[i]).width()) > mcloud.merlin_search_term['r']){
				mcloud.merlin_search_term['r'] = jQuery(rj_selectors[i]).position().left+jQuery(rj_selectors[i]).width();
			}
			//toppier?
			if(jQuery(rj_selectors[i]).position().top < mcloud.merlin_search_term['t']){
				mcloud.merlin_search_term['t'] = jQuery(rj_selectors[i]).position().top;
			}
			//more bottomsome?
			if((jQuery(rj_selectors[i]).position().top+jQuery(rj_selectors[i]).height()) > mcloud.merlin_search_term['b']){
				mcloud.merlin_search_term['b'] = jQuery(rj_selectors[i]).position().top+jQuery(rj_selectors[i]).height();
			}
		}
	}
	function place_thes_terms(carefully){
		
		place_term("#merlin_search_term", 0.5, 0.5, 0.5, 0.5);
		if(!carefully){
			place_term(".thes_up", 0.5, 0.5, 0.1, 1);
		}else if(jQuery(".thes_up").find("ul").length==0){
			place_term(".thes_up", 0.5, 0.5, 0.1, 1);
		}
		if(!carefully){
			place_term(".thes_down", 0.5, 0.5, 0.85, 0);
		}else if(jQuery(".thes_down").find("ul").length==0){
			place_term(".thes_down", 0.5, 0.5, 0.85, 0);
		}
		place_term(".thes_left", 0.30, 0.75, 0.57, 0);
		place_term(".thes_right", 0.78, 0.25, 0.43, 0.5);
		rejig_avoid_coords([".thes_left", ".thes_right"]);

	}
	function make_list_avoid(ul, avoid_coords, unique, rec){
		jQuery(ul).find("li").each(function(){
			var left = jQuery(this).position().left;
			var top = jQuery(this).position().top;
			var right = left + jQuery(this).width();
			var bottom = top + jQuery(this).height();
			var obs_x = false;
			var obs_y = false;
			if(left > avoid_coords['l'] && left < avoid_coords['r']) obs_x = true;
			if(right > avoid_coords['l'] && right < avoid_coords['r']) obs_x = true;
			if(right > avoid_coords['r'] && left < avoid_coords['l']) obs_x = true;
			if(top > avoid_coords['t'] && top < avoid_coords['b']) obs_y = true;
			if(bottom > avoid_coords['t'] && bottom < avoid_coords['b']) obs_y = true;
			if(top < avoid_coords['t'] && bottom > avoid_coords['b']) obs_y = true;
			if(obs_y && obs_x){
				if(top <=  avoid_coords['t'])
					jQuery(this).addClass("above");
				if(bottom >=  avoid_coords['b'])
					jQuery(this).addClass("below");
			}
		});

		jQuery(ul).find("li.above:last").attr("id", "last_up");
	//	jQuery(ul).find("li#last_up").find("a").css({color: 'red'});
			
		jQuery(ul).find("li:first").nextUntil("li#last_up").andSelf().add("li#last_up").wrapAll('<div id="move_up_'+unique+'" class="move"><ul></ul></div>');
		jQuery("div#move_up_"+unique).css({postion: 'absolute'});
		jQuery("div#move_up_"+unique).css({border: '1px dotted white'}); //I truly don't know why this is needed... (ffmac only?)

		jQuery(ul).find("li:first").not("div#move_up_"+unique+" li").find("a").css({color: 'green'});
			
		jQuery(ul).find("li").not("div#move_up_"+unique+" li").wrapAll('<div id="move_down_'+unique+'" class="move"><ul></ul></div>');
		jQuery("div#move_down_"+unique).css({postion: 'absolute'});
		       
		if(jQuery("li#last_up").length>0){ // if there is no last up then no avoidance needed...
			var dist_up = jQuery("li#last_up").position().top+jQuery("li#last_up").height()-avoid_coords['t'];
			var dist_down = avoid_coords['b']-jQuery("div#move_down_"+unique).position().top+dist_up;

			jQuery(ul).find("li").removeClass("above").removeClass("below");
			jQuery(ul).find("li#last_up").attr("id", "");
		
			if(jQuery('div#move_up_'+unique).length){
		
				jQuery('div#move_up_'+unique).animate({
				    marginTop: '-='+dist_up+'px'
				  }, "fast", function() {
					make_list_avoid_y(jQuery("div#move_up_"+unique+" ul"), ".thes_up", true);
				});
		
			}
			if(jQuery("div#move_down_"+unique).length){
				jQuery('div#move_down_'+unique).animate(
					{marginTop: '+='+dist_down+'px'}, 
					"fast", 
					function() {
						make_list_avoid_y(jQuery("div#move_down_"+unique+" ul"), ".thes_down", false);
					}
				);
			}
		}
		jQuery("#cloud a").fadeTo("slow",1);
		mcloud.collapsed = false;
		mcloud.thes_vis = true;
	}
	function make_list_avoid_y(ul, thes_class, up){
		if(up){
			var dist = ((jQuery(thes_class).position().top+jQuery(thes_class).height()) - (jQuery(ul).position().top));
			mcloud.thes_up_dist = dist;
			dist = "-="+dist;
		}else{
			var dist = ((jQuery(ul).position().top+jQuery(ul).height()) - (jQuery(thes_class).position().top));
			mcloud.thes_down_dist = dist;
			dist = "+="+dist;
		}
		jQuery(thes_class).animate(
				{top: dist+'px'}, 
				"fast", 
				function() {
				}
			);
	}

	String.prototype.ucfirst = function () {

	    // Split the string into words if string contains multiple words.
	    var x = this.split(/\s+/g);

	    for (var i = 0; i < x.length; i++) {

		// Splits the word into two parts. One part being the first letter,
		// second being the rest of the word.
		var parts = x[i].match(/(\w)(\w*)/);

		// Put it back together but uppercase the first letter and
		// lowercase the rest of the word.
		x[i] = parts[1].toUpperCase() + parts[2].toLowerCase();
	    }

	    // Rejoin the string and return.
	    return x.join(' ');
	};

	function importScript(url){

		jQuery.ajax({
			type: "GET",
			url: url,
			async: false,
			success: function(js){
				eval(js);
			},
			error: function (data, status, e){
				if(debug) console.log("Request failed: "+status+"\n"+url);
			}
		});
	}


	var debug = true;

	if(typeof(console) === 'undefined' || console == null)
		debug=false;
	jQuery(document).ready(function(){

		importScript("../js/jquery-ui-1.7.2.custom.min.js");
		importScript("../js/jquery.url.packed.js");
//		importScript("../js/jquery.comments.js");
		importScript("../js/date.js");
		importScript("../js/fancyzoom.js");

		var mtd = jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('today').moveToFirstDayOfMonth())+":"+jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('today'));
		var tpm = jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('1 month ago').moveToFirstDayOfMonth())+":"+jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('1 month ago').moveToLastDayOfMonth());
		var ytd = jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('-1y').moveToMonth(0).moveToFirstDayOfMonth())+":"+jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('today'));
		var tpy = jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('-2y').moveToMonth(0).moveToFirstDayOfMonth())+":"+jQuery.datepicker.formatDate('yy-mm-dd', Date.parse('-1y').moveToMonth(11).moveToLastDayOfMonth());
		var years ="";
		for(i=jQuery.datepicker.formatDate('yy', Date.parse('today')); i> 1969; i--){
			years +='<option value="'+i+'">'+i+'</option>';
		}
		jQuery("#daterange").append('<option value="">All</option>'+
					'<option value="'+mtd+'">Month to date</option>'+
					'<option value="'+tpm+'">The previous Month</option>'+
					'<option value="'+ytd+'">Year to date</option>'+
					'<option value="'+tpy+'">The previous Year</option>'+
					'<option value="dr">Enter my own dates</option>');
		jQuery("#daterange").change(function(){
			if(jQuery(this).val()=="dr"){
				jQuery(this).after('<div style="clear: both;"><label for="date_from">from:</label><input type="text" name="date_from" id="date_from">&nbsp;<label for="date_to">to:</label><input type="text" name="date_to" id="date_to"></div>');
				jQuery("#date_from").datepicker();
//				jQuery("#date_from").datepicker({dateFormat: 'yy-mm-dd', changeYear: true, defaultDate: 1, yearRange: '1970:'+jQuery.datepicker.formatDate('yy', Date.parse('today'))});

//				jQuery("#date_to").datepicker({dateFormat: 'yy-mm-dd', changeYear: true, defaultDate: 1, yearRange: '1970:'+jQuery.datepicker.formatDate('yy', Date.parse('today'))});
			}
		});
		jQuery("#search").addClass("active");
	//	update_search_string();
		search.desc_length=400;
		jQuery("#search_form").submit(function(){
			jQuery("#terms_cloud").html('<div class="fieldset term_loader"><img src="/images/ajax-loader.gif"/></div>');
			jQuery("#terms_cloud .term_loader").width(jQuery("#terms").width()-10);
			jQuery("#terms_cloud .term_loader").height(jQuery("#form-content").height());
			jQuery("#terms ul").html('');
			jQuery("#results").html('');
			do_search(jQuery(this));
			return false;
		});	
/*
		jQuery("#search_history").click(function(){
			get_search_history(true);
			return false;
		});	
		jQuery("#marked_list").click(function(){
			get_marked_list(true);
			return false;
		});	
*/
//		jQuery('#search_feedback').fancyZoom({directory: config.mer_dir+'/images', width: 750, close_pos: 780});
		jQuery("#zoom_close").click(function(){
			if(jQuery(this).attr("rel") == "embedded_survey") { jQuery("#search").addClass("active"); jQuery("#search_feedback").removeClass("active"); }
		});
		jQuery("#browse").click(function(){
			browse();
			return false;
		});
		jQuery("#search").click(function(){
			jQuery("#form-content div.cont").remove();
			jQuery("#form-content").append(jQuery(search.search_form));
			// jQuery.live() makes other things not work so explicitly re-binding submit handler
			jQuery("#search_form").submit(function(){
				jQuery("#terms_cloud").html('<div class="fieldset term_loader"><img src="'+config.mer_dir+'/images/ajax-loader.gif"/></div>');
				jQuery("#terms_cloud .term_loader").width(jQuery("#terms").width()-10);
				jQuery("#terms_cloud .term_loader").height(jQuery("#form-content").height());
				jQuery("#terms ul").html('');
				jQuery("#results").html('');
				do_search(jQuery(this));
				return false;
			});	

			return false;
		});	

		jQuery("#MainNav a").click(function(){
			jQuery(this).closest("li").siblings().find("a").removeClass("active");
			jQuery(this).addClass("active");
		});
//		get_marked_list();
		jQuery('.fieldset h2 a').fancyZoom({directory: config.mer_dir+'/images', width: 600});
		jQuery("#terms div.fieldset").height(jQuery("#form-content").height());
		jQuery("#terms_cloud div.fieldset").width(jQuery("#terms").width()-3);
		jQuery("#results div.fieldset").height(jQuery("#form-content").height());
		jQuery("#screencast").width(jQuery("#terms").width()-3);
		var sc_w = jQuery("#screencast object").width();
		if(sc_w == 0) { sc_w = jQuery("#screencast object").css("width"); sc_w = sc_w.substr(0,sc_w.length-2); };
		var sc_marg = (jQuery("#screencast").width() - sc_w )/2;
		jQuery("#screencast object").css({'margin-left': sc_marg});

	});

//})(jQuery);
